package com.mango.iot.gateway.http.controller;

import com.alibaba.fastjson.JSONObject;
import com.mango.iot.gateway.http.consts.AppBizException;
import com.mango.iot.gateway.http.consts.CommonConstant;
import com.mango.iot.gateway.http.consts.JsonResult;
import com.mango.iot.gateway.http.consts.ResultCode;
import com.mango.iot.gateway.http.srv.TokenService;
import com.mango.iot.gateway.http.srv.TopicService;
import com.mango.iot.gateway.http.srv.dto.DeviceInfo;
import com.mango.iot.gateway.http.utils.AppBizExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 设备上报数据接口
 *
 * @author liangfeihu
 * @since 2021/8/24 13:34
 */
@Slf4j
@RestController
public class TopicController {

    @Autowired
    private TopicService topicService;

    @Autowired
    private TokenService tokenService;

    /**
     * 属性上报
     */
    @PostMapping("/{productId}/{deviceId}/properties/report")
    public JsonResult propertyReport(HttpServletRequest httpServletRequest,
                                     @PathVariable("productId") String productId,
                                     @PathVariable("deviceId") String deviceId,
                                     @RequestBody JSONObject jsonObject) throws AppBizException {
        String topic = httpServletRequest.getRequestURI();
        log.info("[topic] productId={} deviceId={} property params={}", productId, deviceId, jsonObject.toJSONString());

        String token = httpServletRequest.getHeader(CommonConstant.TOKEN_HEADER);
        DeviceInfo deviceInfo = tokenService.getDeviceInfoInCache(token);
        if (!topic.contains(deviceInfo.getProductKey()) || !topic.contains(deviceInfo.getDeviceNo())) {
            log.warn("[topic] topic={} deviceInfo={}", topic, JSONObject.toJSONString(deviceInfo));
            throw AppBizExceptionUtil.build(ResultCode.TOPIC_INVALID);
        }

        // 转发到MQS
        topicService.handleUpMessage(topic, jsonObject);
        return JsonResult.success("report property data success");
    }

    /**
     * 事件上报
     */
    @PostMapping("/{productId}/{deviceId}/event/{eventId}")
    public JsonResult eventReport(HttpServletRequest httpServletRequest,
                                  @PathVariable("productId") String productId,
                                  @PathVariable("deviceId") String deviceId,
                                  @PathVariable("eventId") String eventId,
                                  @RequestBody JSONObject jsonObject) throws AppBizException {
        String topic = httpServletRequest.getRequestURI();
        log.info("[topic] productId={} deviceId={} eventId={} params={}", productId, deviceId, eventId, jsonObject.toJSONString());

        String token = httpServletRequest.getHeader(CommonConstant.TOKEN_HEADER);
        DeviceInfo deviceInfo = tokenService.getDeviceInfoInCache(token);
        if (!topic.contains(deviceInfo.getProductKey()) || !topic.contains(deviceInfo.getDeviceNo())) {
            log.warn("[topic] topic={} deviceInfo={}", topic, JSONObject.toJSONString(deviceInfo));
            throw AppBizExceptionUtil.build(ResultCode.TOPIC_INVALID);
        }

        // 转发到MQS
        topicService.handleUpMessage(topic, jsonObject);
        return JsonResult.success("report property data success");
    }

}
